package com.jiangyao.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jiangyao.common.constants.CacheConstants;
import com.jiangyao.common.constants.ConfigConstants;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.JsonUtil;
import com.jiangyao.common.utils.MD5util;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.component.RedisComponent;
import com.jiangyao.dao.IClassSubjectDao;
import com.jiangyao.dao.IClassUserScoreDao;
import com.jiangyao.dao.IClassUserScoreSemesterDao;
import com.jiangyao.dao.IUserDao;
import com.jiangyao.manager.IntegralManager;
import com.jiangyao.model.dto.backend.ClassUserScoreDTO;
import com.jiangyao.model.dto.backend.ClassUserScoreEditDTO;
import com.jiangyao.model.dto.backend.ClassUserScoreListPageDTO;
import com.jiangyao.model.dto.backend.ClassUserScoreSemesterDTO;
import com.jiangyao.model.dto.backend.ClassUserScoreSemesterListDTO;
import com.jiangyao.model.dto.backend.ClassUserScoreSemesterQueryDTO;
import com.jiangyao.model.entity.ClassUserScore;
import com.jiangyao.model.entity.ClassUserScoreSemester;
import com.jiangyao.model.entity.User;
import com.jiangyao.model.vo.AdminUserSessionVO;
import com.jiangyao.model.vo.backend.ClassUserScoreListVO;
import com.jiangyao.model.vo.backend.ClassUserScoreSemesterListVO;
import com.jiangyao.model.vo.backend.ClassUserScoreSubjectVO;
import com.jiangyao.service.ClassUserScoreService;
import com.jiangyao.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 学员学分信息 服务实现类
 * </p>
 *
 * @author xiangyan
 * @since 2020-08-16
 */
@Slf4j
@Service
public class ClassUserScoreServiceImpl extends BaseServiceImpl<IClassUserScoreDao, ClassUserScore> implements ClassUserScoreService {

	@Autowired
	private IClassUserScoreDao classUserScoreDao;
	@Autowired
	private IClassSubjectDao classSubjectDao;
	@Autowired
	private IClassUserScoreSemesterDao classUserScoreSemesterDao;
	@Autowired
	private RedisComponent redisComponent;
	@Autowired
	private DozerBeanMapper dozerBeanMapper;
	@Autowired
	private IUserDao userDao;
	@Autowired
	private ConfigService configService;
	@Autowired
	private IntegralManager integralManage;

	/**
	 * 检查组织班级权限
	 *
	 * @param orgId   组织ID
	 * @param classId 班级ID
	 */
	private void checkAuthority(Integer orgId, Integer classId) {
		AdminUserSessionVO sessionVO = getAdminLoginSession();
		if (!CollectionUtils.isEmpty(sessionVO.getOrgIdList()) && !sessionVO.getOrgIdList().contains(orgId)) {
			throw new ServerException(100, "该组织班级下无操作权限");
		}
		if (!CollectionUtils.isEmpty(sessionVO.getClassIdList()) && !sessionVO.getClassIdList().contains(classId)) {
			throw new ServerException(100, "该组织班级下无操作权限");
		}
	}

	@Override
	public List<ClassUserScoreSemesterListVO> getSemesterList(ClassUserScoreSemesterQueryDTO listDTO) {
		return classUserScoreSemesterDao.getSemesterList(listDTO);
	}

	@Override
	public void updateSemesterList(ClassUserScoreSemesterListDTO listDTO) {
		if (CollectionUtils.isEmpty(listDTO.getSubjectList())) {
			return;
		}
		Integer orgId = listDTO.getOrgId();
		Integer classId = listDTO.getClassId();
		// 检查组织班级权限
		checkAuthority(orgId, classId);
		// 当前登录用户ID
		Integer adminUserId = getLoginAdminUserId();
		// 学期名称
		String semesterName = listDTO.getSemesterName();

		for (ClassUserScoreSemesterDTO semesterSubject : listDTO.getSubjectList()) {
			// 新建
			if (semesterSubject.getId() == null || semesterSubject.getId() == 0) {
				ClassUserScoreSemester cuss = dozerBeanMapper.map(semesterSubject, ClassUserScoreSemester.class);
				cuss.setId(null);
				cuss.setOrgId(orgId);
				cuss.setClassId(classId);
				cuss.setSemesterName(semesterName);
				cuss.setCreateTime(new Date());
				cuss.setCreateAdminId(adminUserId);
				classUserScoreSemesterDao.insert(cuss);
			} else {
				// 编辑
				UpdateWrapper<ClassUserScoreSemester> uw = new UpdateWrapper<>();
				uw.eq("id", semesterSubject.getId()).eq("org_id", orgId).eq("class_id", classId);
				uw.set("semester_name", semesterName).set("subject_name", semesterSubject.getSubjectName());
				uw.set("credit", semesterSubject.getCredit()).set("sort_order", semesterSubject.getSortOrder());
				classUserScoreSemesterDao.update(null, uw);
			}
		}
	}

	@Override
	public void deleteSemesterList(ClassUserScoreSemesterQueryDTO delDTO) {
		Integer orgId = delDTO.getOrgId();
		Integer classId = delDTO.getClassId();
		// 检查组织班级权限
		checkAuthority(orgId, classId);
		UpdateWrapper<ClassUserScoreSemester> uw = new UpdateWrapper<>();
		uw.in("id", delDTO.getCussIdList()).eq("org_id", orgId).eq("class_id", classId);
		uw.set("status", 0);
		classUserScoreSemesterDao.update(null, uw);
	}

	@Override
	public void downloadImportTemplate(HttpServletResponse response, String dtoJson) {
		ClassUserScoreDTO dto;
		try {
			dto = JsonUtil.parse(dtoJson, ClassUserScoreDTO.class);
			if (dto == null || dto.getOrgId() == null || dto.getOrgId() < 1
					|| dto.getClassId() == null || dto.getClassId() < 1
					|| StringUtils.isBlank(dto.getSemesterName())) {
				throw new ServerException(100, "组织ID,班级ID,学期ID有误");
			}
		} catch (Exception e) {
			throw new ServerException(100, "组织ID,班级ID,学期ID有误");
		}
		// 检查组织班级权限
		checkAuthority(dto.getOrgId(), dto.getClassId());
		try {
			// 获取课堂教学 列表
			QueryWrapper<ClassUserScoreSemester> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("org_id", dto.getOrgId()).eq("class_id", dto.getClassId()).eq("semester_name", dto.getSemesterName());
			queryWrapper.eq("status", 1);
			queryWrapper.orderByAsc("sort_order");
			queryWrapper.select("id", "subject_name");
			List<ClassUserScoreSemester> classUserScoreSemesterList = classUserScoreSemesterDao.selectList(queryWrapper);

			// 获取模板表格头
			List<List<String>> head = headImportTemplate(dto, classUserScoreSemesterList);

			String fileName = URLEncoder.encode("成绩导入模板", "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
			EasyExcel.write(response.getOutputStream()).head(head).sheet("成绩导入（不要修改表头）").doWrite(Lists.newArrayList());
		} catch (Exception e) {
			log.error("下载成绩导入模板失败，error:{}", e.getMessage(), e);
		}
	}

	/**
	 * 成绩导入模板-表头生成
	 *
	 * @param dto                        dto
	 * @param classUserScoreSemesterList 班级专业成绩学期课程 列表
	 * @return 表头
	 */
	private List<List<String>> headImportTemplate(ClassUserScoreDTO dto, List<ClassUserScoreSemester> classUserScoreSemesterList) {


		// 导入成员成绩头部信息--数据ID集合
		List<Integer> headDataIdList = new ArrayList<>();
		headDataIdList.add(dto.getOrgId());
		headDataIdList.add(dto.getClassId());
		classUserScoreSemesterList.forEach(cs -> headDataIdList.add(cs.getId()));
		String headDataIdStr = StringUtils.list2string(headDataIdList);
		// 模板编号
		String templateSn = MD5util.generateSymbol(headDataIdStr);
		redisComponent.set(CacheConstants.CACHE_KEY_CLASSUSERSCORE_TEMP_SN + templateSn, headDataIdStr, CacheConstants.CACHE_TIME_7_DAY);


		List<List<String>> list = new ArrayList<>();
		List<String> head0 = new ArrayList<>();
		head0.add("导入编号");
		head0.add("学员姓名");
		List<String> head1 = new ArrayList<>();
		head1.add(templateSn);
		head1.add("手机号");
		list.add(head0);
		list.add(head1);
		if (CollectionUtils.isEmpty(classUserScoreSemesterList)) {
			list.add(Lists.newArrayList("", "先创建学期与专业课程"));
			return list;
		}

		for (int i = 0; i < classUserScoreSemesterList.size(); i++) {
			List<String> head = new ArrayList<>();
			head.add("");
			head.add(classUserScoreSemesterList.get(i).getSubjectName());
			list.add(head);
		}
		return list;
	}


	@Override
	public void importScore(MultipartFile file) {
		List<LinkedHashMap<Integer, String>> excelRowList;
		try {
			excelRowList = EasyExcel.read(file.getInputStream(), new NoModelDataListener()).headRowNumber(0).sheet().doReadSync();
		} catch (Exception e) {
			log.error("导入成绩失败,error:{}", e.getMessage(), e);
			String errorMsg = e.getMessage();
			if (StringUtils.isNotEmpty(errorMsg)) {
				errorMsg = errorMsg.replace("com.jiangyao.common.exception.ServerException:", "");
			}
			throw new ServerException(100, errorMsg);
		}
		if (CollectionUtils.isEmpty(excelRowList) || excelRowList.size() < 3) {
			throw new ServerException(100, "文件为空");
		}
		String templateSn = excelRowList.get(0).get(1);
		String headDataIdStr = redisComponent.getObject(CacheConstants.CACHE_KEY_CLASSUSERSCORE_TEMP_SN + templateSn);
		if (StringUtils.isBlank(headDataIdStr)) {
			throw new ServerException(100, "模板编号无效，请重新下载导入模板");
		}
		List<Integer> headDataIdList = StringUtils.String2IntList(headDataIdStr);
		Integer orgId = headDataIdList.get(0);
		Integer classId = headDataIdList.get(1);
		// 检查组织班级权限
		checkAuthority(orgId, classId);

		// 转换成成员专业成绩集合
		List<ClassUserScore> classUserScoreList = convert2ClassUserScore(headDataIdList, excelRowList);

		// 保存成绩数据到数据库
		saveClassUserScore(classUserScoreList);

	}

	/**
	 * 转换成成员专业成绩集合
	 *
	 * @param headDataIdList 模板表头数据ID集合（专业成绩学期科目id）
	 * @param excelRowList   excel行数据
	 * @return 成员专业成绩集合
	 */
	private List<ClassUserScore> convert2ClassUserScore(List<Integer> headDataIdList, List<LinkedHashMap<Integer, String>> excelRowList) {
		// 组织ID
		Integer orgId = headDataIdList.get(0);
		// 班级ID
		Integer classId = headDataIdList.get(1);
		// 过于多余数据
		headDataIdList = headDataIdList.subList(2, headDataIdList.size());
		excelRowList = excelRowList.subList(2, excelRowList.size());
		Map<String, ClassUserScore> userPhoneScoreMap = Maps.newHashMapWithExpectedSize(excelRowList.size() * headDataIdList.size());
		List<String> userPhoneList = Lists.newArrayListWithExpectedSize(userPhoneScoreMap.size());
		for (int i = 0; i < excelRowList.size(); i++) {
			List<String> valueList = Lists.newArrayList(excelRowList.get(i).values());
			for (int j = 2; j < valueList.size(); j++) {
				ClassUserScore classUserScore = new ClassUserScore();
				classUserScore.setCussId(headDataIdList.get(j - 2));
				classUserScore.setScore(new BigDecimal(valueList.get(j)));
				userPhoneScoreMap.put(valueList.get(1) + "_" + headDataIdList.get(j - 2), classUserScore);
				if (!userPhoneList.contains(valueList.get(1))) {
					userPhoneList.add(valueList.get(1));
				}
			}
		}
		// 用户列表
		List<User> userList = userDao.getListByClassUser(orgId, classId, userPhoneList);
		if (CollectionUtils.isEmpty(userList)) {
			return null;
		}
		Date now = new Date();
		Integer adminUserId = getLoginAdminUserId();
		// 成员专业成绩集合
		List<ClassUserScore> classUserScoreList = Lists.newArrayListWithCapacity(userList.size());
		for (User user : userList) {
			for (Integer dataId : headDataIdList) {
				ClassUserScore cus = userPhoneScoreMap.get(user.getUserPhone() + "_" + dataId);
				if (cus != null) {
					cus.setUserId(user.getUserId());
					cus.setCreateTime(now);
					cus.setCreateAdminId(adminUserId);
					classUserScoreList.add(cus);
				}
			}
		}
		return classUserScoreList;
	}

	/**
	 * 保存成绩数据到数据库
	 *
	 * @param classUserScoreList 专业成绩集合
	 */
	private void saveClassUserScore(List<ClassUserScore> classUserScoreList) {
		if (CollectionUtils.isEmpty(classUserScoreList)) {
			return;
		}

		Map<String, ClassUserScore> ClassUserScoreMap = classUserScoreList.stream().collect(Collectors.toMap(cus -> cus.getCussId() + "_" + cus.getUserId(), cus -> cus));
		// 查询数据库已存在的成绩记录
		List<ClassUserScore> existScoreList = classUserScoreDao.getListByCussIdAndUserId(classUserScoreList);
		if (!CollectionUtils.isEmpty(existScoreList)) {
			for (ClassUserScore cus : existScoreList) {
				String key = cus.getCussId() + "_" + cus.getUserId();
				ClassUserScore cus2 = ClassUserScoreMap.get(key);
				cus.setScore(cus2.getScore());
				ClassUserScoreMap.remove(key);
			}
		}
		// 新增成绩记录
		if (!CollectionUtils.isEmpty(ClassUserScoreMap)) {
			this.saveBatch(ClassUserScoreMap.values());
			// 保存积分流水日志-专业成绩
			integralManage.saveIntegralLogForClassUserScore(Lists.newArrayList(ClassUserScoreMap.values()));
		}
		// 修改成绩记录
		if (!CollectionUtils.isEmpty(existScoreList)) {
			this.updateBatchById(existScoreList);
		}
	}


	/**
	 * 直接用map接收数据
	 */
	public static class NoModelDataListener extends AnalysisEventListener<LinkedHashMap<Integer, String>> {
		List<LinkedHashMap<Integer, String>> list = new ArrayList<>();
		// 每行最多单元格个数
		int cellNum = 0;

		@Override
		public void invoke(LinkedHashMap<Integer, String> data, AnalysisContext context) {
			int line = list.size() + 1;
			if (CollectionUtils.isEmpty(data.values())) {
				throw new ServerException(100, "第" + line + "行数据有误");
			}
			List<String> valueList = Lists.newArrayList(data.values());
			// 第一行：导入编号
			if (line == 1 && (valueList.size() < 2 || StringUtils.isBlank(valueList.get(1)))) {
				throw new ServerException(100, "第" + line + "行数据有误，导入编号为空");
			}

			// 第二行：课程科目
			if (line == 2 && valueList.size() < 3) {
				throw new ServerException(100, "第" + line + "行数据有误，没有科目");
			}
			//
			if (line == 2) {
				cellNum = valueList.size();
			}
			if (line > 2) {
				if (cellNum != valueList.size()) {
					throw new ServerException(100, "第" + line + "行数据有误");
				}
				for (int i = 1; i < valueList.size(); i++) {
					String value = valueList.get(i);
					if (StringUtils.isBlank(value)) {
						throw new ServerException(100, "第" + line + "行数据有误");
					}
					value = value.trim();
					if (!NumberUtils.isNumber(value)) {
						throw new ServerException(100, "第" + line + "行数据有误");
					}
				}
			}
			list.add(data);
		}

		@Override
		public void doAfterAllAnalysed(AnalysisContext context) {
		}
	}

	@Override
	public Page<ClassUserScoreListVO> getListPage(ClassUserScoreListPageDTO listPageDTO) {
		Page<ClassUserScoreListVO> page = new Page<>(listPageDTO.getPageNo(), listPageDTO.getPageSize());
		// 获取专业成绩学期课程
		List<ClassUserScoreSemester> semesterSubjectList = getSubjectListBySemesterName(listPageDTO.getOrgId(), listPageDTO.getClassId(), listPageDTO.getSemesterName());
		if (CollectionUtils.isEmpty(semesterSubjectList)) {
			return page;
		}
		// 获取成员列表
		classUserScoreDao.getListPage(page, listPageDTO);
		List<ClassUserScoreListVO> resultList = page.getRecords();
		if (CollectionUtils.isEmpty(resultList)) {
			return page;
		}

		List<Integer> userIdList = resultList.stream().map(ClassUserScoreListVO::getUserId).collect(Collectors.toList());
		listPageDTO.setUserIdList(userIdList);
		// 获取成员专业成绩列表
		List<ClassUserScoreSubjectVO> subjectList = classUserScoreDao.getSubjectList(listPageDTO);
		// 封装匹配成员专业成绩
		resultList = packClassUserScoreListVO(resultList, semesterSubjectList, subjectList);
		page.setRecords(resultList);

		return page;
	}


	/**
	 * 获取专业成绩学期课程
	 *
	 * @param orgId        组织ID
	 * @param classId      班级ID
	 * @param semesterName 学期名称
	 * @return 结果
	 */
	private List<ClassUserScoreSemester> getSubjectListBySemesterName(Integer orgId, Integer classId, String semesterName) {
		QueryWrapper<ClassUserScoreSemester> qw = new QueryWrapper<>();
		qw.eq("org_id", orgId).eq("class_id", classId).eq("semester_name", semesterName);
		qw.eq("status", 1);
		qw.select("id", "credit", "subject_name");
		qw.orderByDesc("sort_order", "id");
		return classUserScoreSemesterDao.selectList(qw);
	}

	/**
	 * @param resultList
	 * @param semesterSubjectList
	 * @param subjectList
	 */
	private List<ClassUserScoreListVO> packClassUserScoreListVO(List<ClassUserScoreListVO> resultList, List<ClassUserScoreSemester> semesterSubjectList, List<ClassUserScoreSubjectVO> subjectList) {
		// 成员专业课程成绩列表（数据库已存在）
		Map<String, ClassUserScoreSubjectVO> classUserScoreSubjectVOMap = subjectList.stream().collect(Collectors.toMap(ClassUserScoreSubjectVO::getDataId, vo -> vo, (k1, k2) -> k1));
		// 班级专业课程默认成绩（当成员没有某课程成绩时，用于补全 该课程0分）
		Map<String, ClassUserScoreSubjectVO> defaultMap = Maps.newHashMapWithExpectedSize(semesterSubjectList.size());
		semesterSubjectList.forEach(s -> {
			ClassUserScoreSubjectVO subjectVO = ClassUserScoreSubjectVO.builder().dataId("0_" + s.getId()).cussId(s.getId()).subjectName(s.getSubjectName()).credit(s.getCredit())
					.score(BigDecimal.ZERO).build();
			defaultMap.put(subjectVO.getDataId(), subjectVO);
		});
		// 循环匹配成员专业成绩
		for (ClassUserScoreListVO vo : resultList) {
			Integer userId = vo.getUserId();
			List<ClassUserScoreSubjectVO> userScoreSubjectList = vo.getSubjectScoreList();
			if (userScoreSubjectList == null) {
				userScoreSubjectList = Lists.newArrayListWithCapacity(defaultMap.size());
			}

			for (ClassUserScoreSemester subject : semesterSubjectList) {
				Integer cussId = subject.getId();
				String dataId = userId + "_" + cussId;
				ClassUserScoreSubjectVO subjectScore = classUserScoreSubjectVOMap.get(dataId);
				if (subjectScore == null) {
					subjectScore = dozerBeanMapper.map(defaultMap.get("0_" + cussId), ClassUserScoreSubjectVO.class);
					subjectScore.setUserId(userId);
				}
				userScoreSubjectList.add(subjectScore);
			}
			vo.setSubjectScoreList(userScoreSubjectList);
		}
		return resultList;
	}

	@Override
	public void export(HttpServletResponse response, ClassUserScoreListPageDTO listPageDTO) {
		try {
			// 查询班级成员专业成绩列表
			listPageDTO.setPageNo(1);
			listPageDTO.setPageSize(Integer.valueOf(configService.getValueFromCache(ConfigConstants.EXCEL_EXPORT_LIMIT)));
			Page<ClassUserScoreListVO> page = getListPage(listPageDTO);
			List<ClassUserScoreListVO> scoreVOList = page.getRecords();

			String fileName = URLEncoder.encode(listPageDTO.getSemesterName() + "-专业成绩", "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
			EasyExcel.write(response.getOutputStream()).head(exportHead(scoreVOList)).sheet("专业成绩列表").doWrite(exportRowData(scoreVOList));
		} catch (Exception e) {
			log.error("导出专业成绩失败，error:{}", e.getMessage(), e);
		}
	}

	/**
	 * 导出成绩 表头数据
	 *
	 * @param scoreVOList 成绩列表
	 * @return 结果
	 */
	private List<List<String>> exportHead(List<ClassUserScoreListVO> scoreVOList) {
		List<List<String>> result = new ArrayList<>();
		List<String> head1 = new ArrayList<>();
		List<String> head2 = new ArrayList<>();
		List<String> head3 = new ArrayList<>();
		head1.add("学员ID");
		head2.add("学员姓名");
		head3.add("学员电话");
		result.add(head1);
		result.add(head2);
		result.add(head3);
		if (!CollectionUtils.isEmpty(scoreVOList)) {
			List<ClassUserScoreSubjectVO> subjectScoreList = scoreVOList.get(0).getSubjectScoreList();
			if (!CollectionUtils.isEmpty(subjectScoreList)) {
				subjectScoreList.forEach(subject -> {
					List<String> head = new ArrayList<>();
					head.add(subject.getSubjectName() + "-(学分：" + subject.getCredit() + ")");
					result.add(head);
				});
			}
		}

		return result;
	}

	/**
	 * 导出成绩 行数据
	 *
	 * @param scoreVOList 成绩列表
	 * @return 结果
	 */
	private List<List<String>> exportRowData(List<ClassUserScoreListVO> scoreVOList) {
		List<List<String>> result = new ArrayList<>();
		if (!CollectionUtils.isEmpty(scoreVOList)) {
			scoreVOList.forEach(scoreVO -> {
				List<ClassUserScoreSubjectVO> subjectScoreList = scoreVO.getSubjectScoreList();
				List<String> data = new ArrayList<>();
				data.add(scoreVO.getUserId().toString());
				data.add(scoreVO.getUserName());
				data.add(scoreVO.getUserPhone());
				if (!CollectionUtils.isEmpty(subjectScoreList)) {
					subjectScoreList.forEach(subject -> {
						data.add(subject.getScore().toString());
					});
				}
				result.add(data);
			});
		}
		return result;
	}

	@Override
	public void editUserScore(ClassUserScoreEditDTO editDTO) {
		// 检查组织班级权限
		checkAuthority(editDTO.getOrgId(), editDTO.getClassId());
		QueryWrapper<ClassUserScoreSemester> qw = new QueryWrapper<>();
		qw.eq("org_id", editDTO.getOrgId()).eq("class_id", editDTO.getClassId());
		qw.eq("status", 1);
		qw.select("id");
		List<ClassUserScoreSemester> cussList = classUserScoreSemesterDao.selectList(qw);
		if (CollectionUtils.isEmpty(cussList)) {
			throw new ServerException(100, "班级专业课程不存在");
		}
		List<Integer> cuusIdList = cussList.stream().map(ClassUserScoreSemester::getId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(editDTO.getSubjectList())) {
			return;
		}
		Date now = new Date();
		for (ClassUserScoreEditDTO.ScoreSubjectEditDTO subject : editDTO.getSubjectList()) {
			if (!cuusIdList.contains(subject.getCussId())) {
				continue;
			}

			QueryWrapper<ClassUserScore> scoreQw = new QueryWrapper<>();
			scoreQw.eq("cuss_id", subject.getCussId()).eq("user_id", editDTO.getUserId()).eq("status", 1);
			scoreQw.last(" LIMIT 1");
			scoreQw.select("id", "cuss_id", "user_id");
			ClassUserScore score = classUserScoreDao.selectOne(scoreQw);
			// 新增
			if (score == null) {
				score = new ClassUserScore();
				score.setCussId(subject.getCussId());
				score.setUserId(editDTO.getUserId());
				score.setScore(subject.getScore());
				score.setStatus(1);
				score.setCreateTime(now);
				classUserScoreDao.insert(score);
				// 保存积分流水日志-专业成绩
				integralManage.saveIntegralLogForClassUserScore(Lists.newArrayList(score));
			} else {
				UpdateWrapper<ClassUserScore> uw = new UpdateWrapper<>();
				uw.eq("id", score.getId());
				uw.set("score", subject.getScore());
				classUserScoreDao.update(null, uw);
			}
		}
	}

	@Override
	public ClassUserScoreSemesterListVO getSemesterDetail(ClassUserScoreSemesterQueryDTO listDTO) {
		List<ClassUserScoreSemesterListVO> list = classUserScoreSemesterDao.getSemesterList(listDTO);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}
}
